﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Xml;
using umbraco.cms.businesslogic.member;

namespace Designit.Umb.Newsletter.Bll
{
    public class Unsubscribe
    {
        public static void SendConfirmMail(Member member, Guid guid)
        {

            XmlDocument doc = new XmlDocument();
            string path = @"/config/designit/newsletter/mailSettings.config";
            path = HttpContext.Current.Server.MapPath(path);
            doc.Load(path);
            XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
            string fromMail = xnode.Attributes[1].Value;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='ConfirmUnsubscribe']");
            string confirmUnsubscribe = xnode.Attributes[1].Value;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
            string smtp = xnode.Attributes[1].Value;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
            string smtpPort = xnode.Attributes[1].Value;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
            string smtpAuth = xnode.Attributes[1].Value;

            string confirmPage = confirmUnsubscribe + guid;
            MailMessage unsubMail = new MailMessage(fromMail, member.Email);

            unsubMail.Subject = "Confirm unsubscribtion";

            // SEND IN HTML FORMAT (comment this line to send plain text).
            unsubMail.IsBodyHtml = true;

            //build body
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Dear " + member.LoginName);
            sb.AppendLine("");
            sb.AppendLine("You have chosen to unsubscribe to the following group(s):");

            using (var readerName = umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader(
                    "select * from newsLetterUnsubscribeMember where guid = @guid",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@guid", guid)))
            {
                while (readerName.Read())
                {
                    string groupName =
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<string>(
                            "select text from umbracoNode where id=@id",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id",
                                                                                        readerName.GetInt("groupId")));
                    sb.AppendLine(groupName);
                }
            }

            sb.AppendLine("To confirm your unsubscribtion please click the link below");
            sb.AppendLine(confirmPage);

            // HTML Body (remove HTML tags for plain text).
            unsubMail.Body = sb.ToString();


            SmtpClient cl = new SmtpClient(smtp, Int32.Parse(smtpPort));

            if (smtpAuth == "true")
            {
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
                string userId = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                string password = xnode.Attributes[1].Value;
                cl.Credentials = new NetworkCredential(userId, password);
            }
            cl.Send(unsubMail);

        }

        public static void UnsubscribeAll(Member member)
        {
            bool changes = false;
            MemberGroup[] memberGroup = MemberGroup.GetAll;
            Guid guid = Guid.NewGuid();
            foreach (MemberGroup group in memberGroup)
            {

                if (group.HasMember(member.Id))
                {                  
                    UnsubscribeNotify(member, group, guid);
                    ConfirmUnsubscribe.Confirm(guid.ToString());

                    //changes = true;
                }
            }
            //if (changes)
            //{
            //    SendConfirmMail(member, guid);
            //}
        }

        public static void UnsubscribeToGroup(Member member, MemberGroup memberGroup)
        {
            bool changes = false;
            Guid guid = Guid.NewGuid();
            if (!memberGroup.HasMember(member.Id)) return;

            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@memberId", member.Id);
            UnsubscribeNotify(member, memberGroup, guid);
            ConfirmUnsubscribe.Confirm(guid.ToString());
        }

        public static void UnsubscribeNotify(Member member, MemberGroup memberGroup, Guid guid)
        {
            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("insert into newsLetterUnsubscribeMember(guid, groupId, memberId) values(@guid, @groupId, @memberId)",
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@guid", guid),
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@groupId", memberGroup.Id),
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@memberId", member.Id));

        }
    }
}
